{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc422f24",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import font_manager\n",
    "# 导入工具库\n",
    "from PyEMD import EMD, Visualisation\n",
    "from scipy.io import loadmat\n",
    "from scipy.signal import hilbert\n",
    "import math\n",
    "from PyEMD import EEMD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bde38f13",
   "metadata": {},
   "outputs": [],
   "source": [
    "all_bcg_data = pd.read_csv('./one_bcg.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c49daecb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 信号归一化\n",
    "def Standard(data):\n",
    "    class  StandardScaler:\n",
    "        def __init__(self):\n",
    "            self.mean_ = None\n",
    "            self.scale_ = None\n",
    "        def fit(self,X):\n",
    "            '''根据训练数据集X获得数据的均值和方差'''\n",
    "            self.mean_ = np.array([np.mean(X[:])])\n",
    "            self.scale_ = np.array([np.std(X[:])])\n",
    "            return self\n",
    "        def transform(self,X):\n",
    "            '''将X根据Standardcaler进行均值方差归一化处理'''\n",
    "            resX = np.empty(shape=X.shape,dtype=float)\n",
    "    #         for col in range(X.shape[1]):\n",
    "            resX[:] = (data[:]-self.mean_) / (self.scale_)\n",
    "            return resX\n",
    "\n",
    "    StandardScaler = StandardScaler()\n",
    "    StandardScaler.fit(data)\n",
    "    nor_data = StandardScaler.transform(data)\n",
    "    return nor_data\n",
    "# 定义hht变换函数\n",
    "def myhht(y,t):\n",
    "    fs = 1/(t[2]-t[1])\n",
    "    hy = hilbert(y)                                       # 希尔伯特变换\n",
    "    amp = abs(hy)                                         # 计算幅值\n",
    "    phase = np.angle(hy)                                # 计算相位\n",
    "    pha = np.unwrap(phase)                              # 去除相位2pi跃变\n",
    "    fre = abs(fs*np.diff(pha/2/np.pi))                    # 计算频率并进行坐标变换\n",
    "    return amp,fre,pha,phase                                   # 返回幅值，频率和相位\n",
    "\n",
    "# def Get_phase(bcg):\n",
    "#     # 500Hz,间隔0.002\n",
    "#     t = np.arange(0,bcg.size/500, 0.002)\n",
    "#     amp,fre,pha,phase = myhht(bcg,t)\n",
    "#     return phase\n",
    "\n",
    "# 定义emd可视化函数,i表示IMF i\n",
    "def emd_visualisation(bcg,i):\n",
    "    t = np.arange(0,bcg.size/500, 0.002)\n",
    "    # 提取imfs和剩余信号res\n",
    "    emd = EMD()\n",
    "    emd.emd(bcg)\n",
    "    imfs, res = emd.get_imfs_and_residue()\n",
    "    # 绘制 IMF\n",
    "    vis = Visualisation()\n",
    "    vis.plot_imfs(imfs=imfs, residue=res, t=t, include_residue=True)\n",
    "\n",
    "    Y=imfs[i]\n",
    "    amp,fre,pha,phase = myhht(Y,t)\n",
    "    plt.figure(figsize=(15,5))\n",
    "    plt.plot(t,Y)                                             # 图形绘制\n",
    "    plt.title('BCG Signal-IMF')\n",
    "    plt.xlabel('Time')\n",
    "    plt.ylabel('am')\n",
    "\n",
    "    plt.figure(figsize=(15,5))\n",
    "    plt.plot(t,phase,'r')                             # 图形绘制\n",
    "    plt.title('BCG-phase')\n",
    "    plt.xlabel('Time')\n",
    "    plt.ylabel('phase')\n",
    "    plt.show()\n",
    "    \n",
    "# eemd算法，加白噪声，但效果一般\n",
    "# 定义emd可视化函数,i表示IMF i\n",
    "def eemd_visualisation(bcg,i):\n",
    "    t = np.arange(0,bcg.size/500, 0.002)\n",
    "    # 提取imfs和剩余信号res\n",
    "    eemd = EEMD()\n",
    "    emd = eemd.EMD\n",
    "    emd.extrema_detection=\"parabol\"\n",
    "    imfs= eemd.eemd(bcg,t)\n",
    "#     imfs, res = emd.get_imfs_and_residue()\n",
    "    # 绘制 IMF\n",
    "#     vis = Visualisation()\n",
    "#     vis.plot_imfs(imfs=imfs, t=t, include_residue=True)\n",
    "\n",
    "    Y=imfs[i]\n",
    "    amp,fre,pha,phase = myhht(Y,t)\n",
    "    plt.figure(figsize=(15,5))\n",
    "    plt.plot(t,Y)                                             # 图形绘制\n",
    "    plt.title('BCG Signal-IMF')\n",
    "    plt.xlabel('Time')\n",
    "    plt.ylabel('am')\n",
    "\n",
    "    plt.figure(figsize=(15,5))\n",
    "    plt.plot(t,phase,'r')                             # 图形绘制\n",
    "    plt.title('BCG-phase')\n",
    "    plt.xlabel('Time')\n",
    "    plt.ylabel('phase')\n",
    "    plt.show()\n",
    "def eemd_phase(bcg,i):\n",
    "    t = np.arange(0,bcg.size/500, 0.002)\n",
    "    # 提取imfs和剩余信号res\n",
    "    eemd = EEMD()\n",
    "    emd = eemd.EMD\n",
    "    emd.extrema_detection=\"parabol\"\n",
    "    imfs= eemd.eemd(bcg,t)\n",
    "\n",
    "    Y=imfs[i]\n",
    "    amp,fre,pha,phase = myhht(Y,t)\n",
    "    return phase"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8e6890a",
   "metadata": {},
   "outputs": [],
   "source": [
    "first_phase_oneperson=[]\n",
    "second_phase_oneperson=[]\n",
    "for i in range(29):\n",
    "    phase1=eemd_phase(all_bcg_data.iloc[:,:5000].values[i],4)\n",
    "    first_phase_oneperson.append(phase1)\n",
    "    phase2=eemd_phase(all_bcg_data.iloc[:,5000:10000].values[i],4)\n",
    "    second_phase_oneperson.append(phase2)\n",
    "first_phase_oneperson=pd.DataFrame(first_phase_oneperson)\n",
    "second_phase_oneperson=pd.DataFrame(second_phase_oneperson)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67e94a60",
   "metadata": {},
   "outputs": [],
   "source": [
    "first_phase_oneperson.to_csv('first_phase_oneperson.csv', index=0)\n",
    "second_phase_oneperson.to_csv('second_phase_oneperson.csv', index=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a311cb29",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9576302e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
